package xyz.lwm.lazycat.transaction;

import xyz.lwm.lazycat.annotation.Bean;
import xyz.lwm.lazycat.annotation.Configuration;
import xyz.lwm.lazycat.aop.Aspect;
import xyz.lwm.lazycat.beans.BeanPostProcessor;
import xyz.lwm.lazycat.beans.BeansException;
import xyz.lwm.lazycat.transaction.execute.TransactionDatasource;

import javax.sql.DataSource;

/**
 * 事务配置, 将替换数据源为事务数据源
 *
 * @author lwm
 */
@Configuration
public class TransactionConfiguration {

    @Bean
    public Aspect transactionAspect() {
        return new TransactionAspect();
    }

    @Bean
    public BeanPostProcessor transactionDatasourceProcessor() {
        return new TransactionDatasourceProcessor();
    }

    /**
     * 事务数据源包装替换，lazycat 事务需要统一管理 connection
     */
    private static class TransactionDatasourceProcessor implements BeanPostProcessor {

        @Override
        public Object processAfterInitialization(Object bean, String beanName) throws BeansException {
            if (bean instanceof DataSource) {
                return new TransactionDatasource((DataSource) bean);
            }
            return bean;
        }

    }

}
